import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 游记JSON文件路径
const TRAVELS_FILE_PATH = path.join(__dirname, '../data/travels.json');
// 用户JSON文件路径
const USERS_FILE_PATH = path.join(__dirname, '../data/users.json');

// 读取游记数据
const readTravelsData = () => {
    try {
        const data = fs.readFileSync(TRAVELS_FILE_PATH, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        console.error('读取游记数据失败:', error);
        return [];
    }
};

// 写入游记数据
const writeTravelsData = (data) => {
    try {
        fs.writeFileSync(TRAVELS_FILE_PATH, JSON.stringify(data, null, 2), 'utf8');
        return true;
    } catch (error) {
        console.error('写入游记数据失败:', error);
        return false;
    }
};

// 读取用户数据
const readUsersData = () => {
    try {
        const data = fs.readFileSync(USERS_FILE_PATH, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        console.error('读取用户数据失败:', error);
        return [];
    }
};

// 写入用户数据
const writeUsersData = (data) => {
    try {
        fs.writeFileSync(USERS_FILE_PATH, JSON.stringify(data, null, 2), 'utf8');
        return true;
    } catch (error) {
        console.error('写入用户数据失败:', error);
        return false;
    }
};

// 关联游记和用户数据
const getEnrichedTravels = () => {
    const travels = readTravelsData();
    const users = readUsersData();

    return travels.map(travel => {
        // 查找与游记作者ID匹配的用户
        if (travel.author && travel.author._id) {
            const user = users.find(u => u.id === travel.author._id);
            if (user) {
                // 丰富作者信息
                travel.author = {
                    ...travel.author,
                    name: user.name || travel.author.nickname,
                    username: user.username
                };
            }
        }
        return travel;
    });
};

/**
 * 注册新用户
 * @route POST /api/admin/register
 * @param {object} req.body - 包含用户注册信息的请求体
 * @returns {object} 注册结果
 */
export const registerUser = (req, res) => {
    try {
        const { username, password, nickname, avatar } = req.body;

        if (!username || !password) {
            return res.status(400).json({
                success: false,
                message: '用户名和密码不能为空'
            });
        }

        // 读取现有用户
        const users = readUsersData();

        // 检查用户名是否已存在
        if (users.some(user => user.username === username)) {
            return res.status(400).json({
                success: false,
                message: '用户名已存在'
            });
        }

        // 生成用户ID
        const newUserId = `user${Date.now()}`;

        // 创建新用户对象
        const newUser = {
            id: newUserId,
            username,
            password,
            nickname: nickname || username,
            avatar: avatar || null,
            role: 'user', // 默认为普通用户
            createdAt: new Date().toISOString()
        };

        // 添加新用户
        users.push(newUser);

        // 保存到文件
        const success = writeUsersData(users);

        if (success) {
            // 返回敏感信息之前删除密码
            const { password, ...userWithoutPassword } = newUser;

            return res.status(201).json({
                success: true,
                message: '用户注册成功',
                user: userWithoutPassword
            });
        } else {
            throw new Error('保存用户数据失败');
        }
    } catch (error) {
        console.error('用户注册失败:', error);
        return res.status(500).json({
            success: false,
            message: '注册失败，服务器错误'
        });
    }
};

/**
 * 获取用户信息
 * @route GET /api/admin/users/:id
 * @param {string} req.params.id - 用户ID
 * @returns {object} 用户信息
 */
export const getUserById = (req, res) => {
    try {
        const { id } = req.params;

        // 读取用户数据
        const users = readUsersData();

        // 查找指定用户
        const user = users.find(u => u.id === id);

        if (!user) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        // 不返回密码
        const { password, ...userWithoutPassword } = user;

        return res.status(200).json({
            success: true,
            user: userWithoutPassword
        });
    } catch (error) {
        console.error('获取用户信息失败:', error);
        return res.status(500).json({
            success: false,
            message: '获取用户信息失败'
        });
    }
};

/**
 * 用户登录
 * @route POST /api/admin/login
 * @param {object} req.body - 包含登录信息的请求体
 * @returns {object} 登录结果和用户信息
 */
export const loginUser = (req, res) => {
    try {
        const { username, password } = req.body;

        if (!username || !password) {
            return res.status(400).json({
                success: false,
                message: '用户名和密码不能为空'
            });
        }

        // 读取用户数据
        const users = readUsersData();

        // 查找匹配的用户
        const user = users.find(u => u.username === username && u.password === password);

        if (!user) {
            return res.status(401).json({
                success: false,
                message: '用户名或密码错误'
            });
        }

        // 不返回密码
        const { password: _, ...userWithoutPassword } = user;

        return res.status(200).json({
            success: true,
            message: '登录成功',
            user: userWithoutPassword
        });
    } catch (error) {
        console.error('用户登录失败:', error);
        return res.status(500).json({
            success: false,
            message: '登录失败，服务器错误'
        });
    }
};

/**
 * 获取所有游记列表(管理员)
 * @route GET /api/admin/travels
 * @param {number} page - 页码，默认为1
 * @param {number} limit - 每页数量，默认为10
 * @param {string} status - 筛选状态(可选)
 * @param {string} search - 搜索关键词(可选)
 * @param {boolean} deleted - 是否仅查询已删除的游记(可选)
 * @returns {object} 包含游记列表和分页信息的对象
 */
export const getAllTravels = (req, res) => {
    try {
        // 获取查询参数
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const status = req.query.status;
        const search = req.query.search || '';
        const deleted = req.query.deleted === 'true';

        // 获取所有游记数据
        let travels = readTravelsData();

        // 根据删除状态筛选
        if (deleted) {
            // 查询已删除的游记
            travels = travels.filter(travel => travel.isDeleted === true);
        } else if (req.query.deleted === 'false') {
            // 明确指定只查询未删除的游记
            travels = travels.filter(travel => !travel.isDeleted);
        }
        // 如果未指定deleted参数，则返回所有游记（包括已删除和未删除）

        // 根据状态筛选
        if (status) {
            travels = travels.filter(travel => travel.status === status);
        }

        // 如果有搜索关键词，进行过滤
        if (search) {
            travels = travels.filter(travel =>
                travel.title.toLowerCase().includes(search.toLowerCase()) ||
                travel.content.toLowerCase().includes(search.toLowerCase()) ||
                (travel.location && travel.location.toLowerCase().includes(search.toLowerCase())) ||
                travel.author.nickname.toLowerCase().includes(search.toLowerCase())
            );
        }

        // 计算分页
        const startIndex = (page - 1) * limit;
        const endIndex = page * limit;
        const total = travels.length;

        // 分页结果
        const paginatedTravels = travels.slice(startIndex, endIndex);

        // 返回结果
        return res.status(200).json({
            success: true,
            count: paginatedTravels.length,
            total,
            totalPages: Math.ceil(total / limit),
            currentPage: page,
            data: paginatedTravels
        });
    } catch (error) {
        console.error('Error getting travels for admin:', error);
        return res.status(500).json({
            success: false,
            error: '获取游记列表失败'
        });
    }
};

/**
 * 审核通过游记
 * @route PUT /api/admin/travels/:id/approve
 * @param {string} id - 游记ID
 * @returns {object} 操作结果
 */
export const approveTravel = (req, res) => {
    try {
        const { id } = req.params;

        // 读取游记数据
        const travels = readTravelsData();

        // 查找指定游记
        const travelIndex = travels.findIndex(t => t.id === id);

        if (travelIndex === -1) {
            return res.status(404).json({
                success: false,
                message: '游记不存在'
            });
        }

        // 更新状态为已通过
        travels[travelIndex].status = 'approved';
        travels[travelIndex].updatedAt = new Date().toISOString();

        // 写入文件
        const success = writeTravelsData(travels);

        if (success) {
            return res.status(200).json({
                success: true,
                message: '游记已通过审核'
            });
        } else {
            throw new Error('保存数据失败');
        }
    } catch (error) {
        console.error('审核通过游记失败:', error);
        return res.status(500).json({
            success: false,
            message: '审核操作失败'
        });
    }
};

/**
 * 拒绝游记
 * @route PUT /api/admin/travels/:id/reject
 * @param {string} id - 游记ID
 * @param {string} reason - 拒绝原因
 * @returns {object} 操作结果
 */
export const rejectTravel = (req, res) => {
    try {
        const { id } = req.params;
        const { reason } = req.body;

        if (!reason) {
            return res.status(400).json({
                success: false,
                message: '拒绝原因不能为空'
            });
        }

        // 读取游记数据
        const travels = readTravelsData();

        // 查找指定游记
        const travelIndex = travels.findIndex(t => t.id === id);

        if (travelIndex === -1) {
            return res.status(404).json({
                success: false,
                message: '游记不存在'
            });
        }

        // 更新状态为已拒绝
        travels[travelIndex].status = 'rejected';
        travels[travelIndex].rejectReason = reason;
        travels[travelIndex].updatedAt = new Date().toISOString();

        // 写入文件
        const success = writeTravelsData(travels);

        if (success) {
            return res.status(200).json({
                success: true,
                message: '已拒绝该游记'
            });
        } else {
            throw new Error('保存数据失败');
        }
    } catch (error) {
        console.error('拒绝游记失败:', error);
        return res.status(500).json({
            success: false,
            message: '拒绝操作失败'
        });
    }
};

/**
 * 删除游记
 * @route DELETE /api/admin/travels/:id
 * @param {string} id - 游记ID
 * @returns {object} 操作结果
 */
export const deleteTravel = (req, res) => {
    try {
        const { id } = req.params;

        // 读取游记数据
        const travels = readTravelsData();

        // 查找指定游记
        const travelIndex = travels.findIndex(t => t.id === id);

        if (travelIndex === -1) {
            return res.status(404).json({
                success: false,
                message: '游记不存在'
            });
        }

        // 先将状态设为已拒绝
        travels[travelIndex].status = 'rejected';
        // 标记为已删除
        travels[travelIndex].isDeleted = true;
        // 如果没有拒绝原因，添加一个默认的拒绝原因
        if (!travels[travelIndex].rejectReason) {
            travels[travelIndex].rejectReason = '此游记已被删除';
        }
        travels[travelIndex].updatedAt = new Date().toISOString();

        // 写入文件
        const success = writeTravelsData(travels);

        if (success) {
            return res.status(200).json({
                success: true,
                message: '游记已删除'
            });
        } else {
            throw new Error('保存数据失败');
        }
    } catch (error) {
        console.error('删除游记失败:', error);
        return res.status(500).json({
            success: false,
            message: '删除操作失败'
        });
    }
};

/**
 * 获取仪表盘统计数据
 * @route GET /api/admin/dashboard
 * @returns {object} 包含系统统计数据和最近游记的对象
 */
export const getDashboardStats = (req, res) => {
    try {
        // 读取游记数据
        const travels = readTravelsData();

        // 读取用户数据 (模拟，实际应从数据库获取)
        const usersCount = 1256; // 实际项目中应该从用户数据库中获取真实数量

        // 计算统计数据
        const totalTravels = travels.length;
        const pendingReviews = travels.filter(travel => travel.status === 'pending' && !travel.isDeleted).length;
        const approvedTravels = travels.filter(travel => travel.status === 'approved' && !travel.isDeleted).length;

        // 获取最近8篇游记，按提交时间降序排序
        const recentTravels = travels
            .filter(travel => !travel.isDeleted) // 过滤掉已删除的
            .sort((a, b) => {
                // 使用updatedAt或createdAt作为排序依据
                const dateA = new Date(a.updatedAt || a.createdAt);
                const dateB = new Date(b.updatedAt || b.createdAt);
                return dateB - dateA; // 降序排序
            })
            .slice(0, 8) // 只取前8篇
            .map(travel => ({
                id: travel.id,
                title: travel.title,
                author: travel.author.nickname,
                submitTime: new Date(travel.createdAt).toLocaleString(),
                status: travel.status
            }));

        // 返回统计数据和最近游记
        return res.status(200).json({
            success: true,
            statistics: {
                totalUsers: usersCount,
                totalTravels,
                pendingReviews,
                approvedTravels
            },
            recentTravels
        });
    } catch (error) {
        console.error('获取仪表盘统计数据失败:', error);
        return res.status(500).json({
            success: false,
            error: '获取统计数据失败'
        });
    }
}; 